<template>
  <div class="route-management">
    <div class="page-header">
      <h1>线路管理</h1>
      <button class="btn btn-primary" @click="showCreateModal = true">
        <i class="icon-plus"></i>
        新增线路
      </button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-group">
          <label>关键词</label>
          <input v-model="searchParams.keyword" type="text" placeholder="请输入搜索关键词" class="form-control" />
        </div>
        <div class="form-actions">
          <button class="btn btn-primary" @click="searchRoutes">搜索</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 线路列表 -->
    <div class="table-section">
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>线路ID</th>
              <th>起点</th>
              <th>终点</th>
              <th>总距离</th>
              <th>预计时间</th>
              <th>委托人</th>
              <th>联系电话</th>
              <th>是否出库</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="route in routes" :key="route.id">
              <td>{{ route.id }}</td>
              <td>{{ route.starting_point }}</td>
              <td>{{ route.destination }}</td>
              <td>{{ route.total_distance }}</td>
              <td>{{ route.estimated_time }}</td>
              <td>{{ route.consignor_name }}</td>
              <td>{{ route.phone }}</td>
              <td>
                <span :class="['status-badge', route.is_out ? 'status-out' : 'status-in']">
                  {{ route.is_out ? '出库' : '入库' }}
                </span>
              </td>
              <td>{{ formatDate(route.createdAt) }}</td>
              <td class="actions">
                <button class="btn btn-sm btn-info" @click="viewRoute(route)">查看</button>
                <button class="btn btn-sm btn-warning" @click="editRoute(route)">编辑</button>
                <button class="btn btn-sm btn-danger" @click="deleteRoute(route)">删除</button>
                <button class="btn btn-sm btn-success" @click="viewRoutePath(route)">查看路径</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">
          <span>共 {{ pagination.totalCount }} 条记录，第 {{ pagination.PageIndex }} / {{ pagination.totalPage }} 页</span>
          <div class="page-size-selector">
            <label>每页显示：</label>
            <select v-model="searchParams.PageSize" @change="changePageSize" class="form-control page-size-select">
              <option value="5">5条</option>
              <option value="10">10条</option>
              <option value="20">20条</option>
              <option value="50">50条</option>
              <option value="100">100条</option>
            </select>
          </div>
        </div>
        <div class="pagination-controls">
          <button class="btn btn-sm" :disabled="pagination.PageIndex <= 1"
            @click="changePage(pagination.PageIndex - 1)">
            上一页
          </button>
          <span class="page-numbers">
            <button v-for="page in getPageNumbers()" :key="page"
              :class="['btn', 'btn-sm', { 'btn-primary': page === pagination.PageIndex }]" @click="changePage(page)">
              {{ page }}
            </button>
          </span>
          <button class="btn btn-sm" :disabled="pagination.PageIndex >= pagination.totalPage"
            @click="changePage(pagination.PageIndex + 1)">
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 创建/编辑线路模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showCreateModal ? '新增线路' : '编辑线路' }}</h3>
          <button class="modal-close" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitRoute">
            <div class="form-row">
              <div class="form-group">
                <label>起点 *</label>
                <div class="input-with-button">
                  <input v-model="routeForm.starting_point" type="text" required class="form-control"
                    placeholder="请输入起点" />
                  <button type="button" class="btn btn-sm btn-info" @click="openMapPicker('start')">选择起点</button>
                </div>
              </div>
              <div class="form-group">
                <label>起点地址 *</label>
                <input v-model="routeForm.start_address" type="text" required class="form-control"
                  placeholder="请输入起点详细地址" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>终点 *</label>
                <div class="input-with-button">
                  <input v-model="routeForm.destination" type="text" required class="form-control"
                    placeholder="请输入终点" />
                  <button type="button" class="btn btn-sm btn-info" @click="openMapPicker('end')">选择终点</button>
                </div>
              </div>
              <div class="form-group">
                <label>终点地址 *</label>
                <input v-model="routeForm.destination_address" type="text" required class="form-control"
                  placeholder="请输入终点详细地址" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>总距离 *</label>
                <div class="input-with-status">
                  <input v-model="routeForm.total_distance" type="text" required class="form-control"
                    :placeholder="isCalculating ? '正在计算距离...' : '请先选择起点和终点'" readonly />
                  <span v-if="isCalculating" class="status-indicator calculating">
                    <i class="icon-loading"></i> 计算中...
                  </span>
                  <span v-else-if="routeForm.total_distance" class="status-indicator success">
                    <i class="icon-check"></i> 已计算
                  </span>
                </div>
              </div>
              <div class="form-group">
                <label>预计时间 *</label>
                <div class="input-with-status">
                  <input v-model="routeForm.estimated_time" type="text" required class="form-control"
                    :placeholder="isCalculating ? '正在计算时间...' : '请先选择起点和终点'" readonly />
                  <span v-if="isCalculating" class="status-indicator calculating">
                    <i class="icon-loading"></i> 计算中...
                  </span>
                  <span v-else-if="routeForm.estimated_time" class="status-indicator success">
                    <i class="icon-check"></i> 已计算
                  </span>
                </div>
              </div>
              <div class="form-group">
                <label>
                  <input v-model="routeForm.is_out" type="checkbox" />
                  出库
                </label>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>委托人 *</label>
                <input v-model="routeForm.consignor_name" type="text" required class="form-control"
                  placeholder="请输入委托人姓名" />
              </div>
              <div class="form-group">
                <label>联系电话 *</label>
                <input v-model="routeForm.phone" type="tel" required class="form-control" placeholder="请输入联系电话" />
              </div>
              <div class="form-group">
                <label>委托单位</label>
                <input v-model="routeForm.consignor_unit" type="text" class="form-control" placeholder="请输入委托单位" />
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label>描述</label>
                <textarea v-model="routeForm.description" class="form-control" rows="3"
                  placeholder="请输入描述信息"></textarea>
              </div>
            </div>


            <div class="modal-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">{{ showCreateModal ? '创建' : '更新' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 查看线路详情模态框 -->
    <div v-if="showViewModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>线路详情</h3>
          <button class="modal-close" @click="closeModal">&times;</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedRoute" class="route-details">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-row">
                <span class="label">线路ID：</span>
                <span class="value">{{ selectedRoute.id }}</span>
              </div>
              <div class="detail-row">
                <span class="label">起点：</span>
                <span class="value">{{ selectedRoute.starting_point }}</span>
              </div>
              <div class="detail-row">
                <span class="label">起点地址：</span>
                <span class="value">{{ selectedRoute.start_address }}</span>
              </div>
              <div class="detail-row">
                <span class="label">终点：</span>
                <span class="value">{{ selectedRoute.destination }}</span>
              </div>
              <div class="detail-row">
                <span class="label">终点地址：</span>
                <span class="value">{{ selectedRoute.destination_address }}</span>
              </div>
              <div class="detail-row">
                <span class="label">总距离：</span>
                <span class="value">{{ selectedRoute.total_distance }}</span>
              </div>
              <div class="detail-row">
                <span class="label">预计时间：</span>
                <span class="value">{{ selectedRoute.estimated_time }}</span>
              </div>
              <div class="detail-row">
                <span class="label">出入库：</span>
                <span :class="['status-badge', selectedRoute.is_out ? 'status-out' : 'status-in']">
                  {{ selectedRoute.is_out ? '出库' : '入库' }}
                </span>
              </div>
            </div>

            <div class="detail-section">
              <h4>委托信息</h4>
              <div class="detail-row">
                <span class="label">委托人：</span>
                <span class="value">{{ selectedRoute.consignor_name }}</span>
              </div>
              <div class="detail-row">
                <span class="label">联系电话：</span>
                <span class="value">{{ selectedRoute.phone }}</span>
              </div>
              <div class="detail-row">
                <span class="label">委托单位：</span>
                <span class="value">{{ selectedRoute.consignor_unit }}</span>
              </div>
              <div class="detail-row" v-if="selectedRoute.description">
                <span class="label">描述：</span>
                <span class="value">{{ selectedRoute.description }}</span>
              </div>
            </div>

            <div class="detail-section">
              <h4>时间信息</h4>
              <div class="detail-row">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatDate(selectedRoute.createdAt) }}</span>
              </div>
              <div class="detail-row">
                <span class="label">创建人：</span>
                <span class="value">{{ selectedRoute.createdBy }}</span>
              </div>
              <div class="detail-row" v-if="selectedRoute.lastModifiedAt">
                <span class="label">最后修改：</span>
                <span class="value">{{ formatDate(selectedRoute.lastModifiedAt) }}</span>
              </div>
              <div class="detail-row" v-if="selectedRoute.lastModifiedBy">
                <span class="label">修改人：</span>
                <span class="value">{{ selectedRoute.lastModifiedBy }}</span>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>

    <!-- 地图选点模态框 -->
    <div v-if="showMapPicker" class="modal-overlay" @click="closeMapPicker">
      <div class="modal-content map-modal" @click.stop>
        <AMapPicker :title="mapPickerTitle" :mode="mapPickerMode" @confirm="handleMapConfirm" @close="closeMapPicker" />
      </div>
    </div>

    <!-- ==================== 路径查看模态框 ==================== -->
    <div v-if="showRoutePathModal" class="modal-overlay" @click="closeRoutePathModal">
      <div class="modal-content route-path-modal" @click.stop>
        <div class="modal-header">
          <h3>线路路径查看</h3>
          <button class="modal-close" @click="closeRoutePathModal">&times;</button>
        </div>
        <div class="modal-body">
          <!-- 加载状态 -->
          <div v-if="isLoadingPath" class="loading-container">
            <div class="loading-spinner">
              <i class="icon-loading"></i>
              <span>正在加载路径数据...</span>
            </div>
          </div>

          <!-- 路径信息和地图 -->
          <div v-else-if="routePathData" class="route-path-container">
            <!-- 路径信息摘要 -->
            <div class="route-summary">
              <div class="summary-item">
                <span class="label">起点：</span>
                <span class="value">{{ routePathData.startPoint?.address }}</span>
              </div>
              <div class="summary-item">
                <span class="label">终点：</span>
                <span class="value">{{ routePathData.endPoint?.address }}</span>
              </div>
              <div class="summary-item">
                <span class="label">总距离：</span>
                <span class="value">{{ routePathData.routeInfo?.distanceText }}</span>
              </div>
              <div class="summary-item">
                <span class="label">预计时间：</span>
                <span class="value">{{ routePathData.routeInfo?.durationText }}</span>
              </div>
              <div class="summary-item" v-if="routePathData.routeInfo?.tollsText">
                <span class="label">过路费：</span>
                <span class="value">{{ routePathData.routeInfo.tollsText }}</span>
              </div>
              <div class="summary-item">
                <span class="label">路径策略：</span>
                <span class="value">{{ routePathData.routeInfo?.strategy }}</span>
              </div>
            </div>

            <!-- 地图容器 -->
            <div class="map-container">
              <div id="routePathMap" class="route-map"></div>
            </div>
          </div>

          <!-- 错误状态 -->
          <div v-else class="error-container">
            <div class="error-message">
              <i class="icon-error"></i>
              <span>路径数据加载失败，请重试</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Toast 通知 -->
  <div v-if="toast.show" :class="['toast', `toast-${toast.type}`]">
    <div class="toast-content">
      <i :class="['toast-icon', getToastIcon()]"></i>
      <span class="toast-message">{{ toast.message }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { Route, Waypoint, Address, PageParams } from '@/types/api'
import { routeApi } from '@/api'
import AMapPicker from '@/components/AMapPicker.vue'

interface MapPoint {
  type: 'start' | 'end'
  lng: number
  lat: number
  address: string
  name: string
}

// 路线搜索参数类型
interface RouteSearchParams {
  PageIndex: number
  PageSize: number
  keyword: string
}

// 响应式数据
const routes = ref<Route[]>([])

// Toast 通知
const toast = reactive({
  show: false,
  type: 'success', // success, error, warning, info
  message: ''
})
const pagination = reactive({
  PageIndex: 1,
  PageSize: 10,
  totalCount: 0,
  totalPage: 0
})

const searchParams = reactive<RouteSearchParams>({
  PageIndex: 1,
  PageSize: 10,
  keyword: ''
})

// 模态框状态
const showCreateModal = ref(false)
const showEditModal = ref(false)
const showViewModal = ref(false)
const showMapPicker = ref(false)
const showRoutePathModal = ref(false) // 路径查看模态框
const mapPickerMode = ref<'start' | 'end'>('start')
const mapPickerTitle = ref('')
const selectedRoute = ref<Route | null>(null)
const routePathData = ref<any>(null) // 存储路径数据
const isLoadingPath = ref(false) // 路径加载状态

// 路线计算相关
const isCalculating = ref(false)
const routeCoordinates = reactive({
  start: { lng: 0, lat: 0 },
  end: { lng: 0, lat: 0 }
})

// 计算路线是否可用
const canCalculateRoute = ref(false)

// 线路表单
const routeForm = reactive({
  id: 0,
  starting_point: '',
  start_address: '',
  destination: '',
  destination_address: '',
  is_out: true,
  consignor_name: '',
  phone: '',
  consignor_unit: '',
  description: '',
  total_distance: '',
  estimated_time: '',
  createdBy: '王大锤',
  lastModifiedBy: '王大锤'
})

// 生命周期
onMounted(() => {
  loadRoutes()
})

// 方法
const loadRoutes = async () => {
  try {
    const response = await routeApi.getRouteList(searchParams)
    if (response.code === 200) {
      // 现在API返回分页数据结构，和订单API一样
      const routeData = response.data
      routes.value = routeData.data
      pagination.totalCount = routeData.totalCount
      pagination.totalPage = routeData.totalPage
      pagination.PageIndex = searchParams.PageIndex
    }
  } catch (error) {
    console.error('Failed to load routes:', error)
  }
}

const searchRoutes = () => {
  searchParams.PageIndex = 1
  pagination.PageIndex = 1
  loadRoutes()
}

const resetSearch = () => {
  Object.assign(searchParams, {
    PageIndex: 1,
    PageSize: 10,
    keyword: ''
  })
  pagination.PageIndex = 1
  pagination.PageSize = 10
  loadRoutes()
}

const changePage = (page: number) => {
  if (page >= 1 && page <= pagination.totalPage) {
    searchParams.PageIndex = page
    pagination.PageIndex = page
    loadRoutes()
  }
}

const changePageSize = () => {
  searchParams.PageIndex = 1
  pagination.PageIndex = 1
  pagination.PageSize = searchParams.PageSize
  loadRoutes()
}

const getPageNumbers = () => {
  const pages = []
  const start = Math.max(1, pagination.PageIndex - 2)
  const end = Math.min(pagination.totalPage, pagination.PageIndex + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
}

const viewRoute = (route: Route) => {
  selectedRoute.value = route
  showViewModal.value = true
}

const editRoute = (route: Route) => {
  Object.assign(routeForm, {
    id: route.id,
    starting_point: route.starting_point || '',
    start_address: route.start_address || '',
    destination: route.destination || '',
    destination_address: route.destination_address || '',
    is_out: route.is_out || true,
    consignor_name: route.consignor_name || '',
    phone: route.phone || '',
    consignor_unit: route.consignor_unit || '',
    description: route.description || '',
    total_distance: route.total_distance || '',
    estimated_time: route.estimated_time || '',
    createdBy: '王大锤'
  })
  showEditModal.value = true
}

const deleteRoute = async (route: Route) => {
  if (confirm(`确定要删除线路 ${route.id} 吗？`)) {
    try {
      const response = await routeApi.deleteRoute(route.id, "王大锤")
      console.log('Deleting route:', route.id)
      if (response.code === 200) {
        showToast('删除线路成功！', 'success')
      }
      loadRoutes()
    } catch (error) {
      console.error('Failed to delete route:', error)
      showToast('删除线路失败，请重试！', 'error')
    }
  }
}

const submitRoute = async () => {
  try {
    if (showCreateModal.value) {
      // 创建线路时，只传递API需要的字段
      const createData = {
        starting_point: routeForm.starting_point,
        start_address: routeForm.start_address,
        destination: routeForm.destination,
        destination_address: routeForm.destination_address,
        is_out: routeForm.is_out,
        consignor_name: routeForm.consignor_name,
        phone: routeForm.phone,
        consignor_unit: routeForm.consignor_unit,
        description: routeForm.description,
        total_distance: routeForm.total_distance,
        estimated_time: routeForm.estimated_time,
        createdBy: routeForm.createdBy
      }
      const response = await routeApi.createRoute(createData)
      console.log('Creating route:', createData)
      if (response.code === 200) {
        showToast('创建线路成功！', 'success')
      }
    } else {
      // 更新线路时，传递完整的表单数据（包含id）
      const response = await routeApi.updateRoute(routeForm)
      console.log('Updating route:', routeForm)
      if (response.code === 200) {
        showToast('更新线路成功！', 'success')
      }
    }
    closeModal()
    loadRoutes()
  } catch (error) {
    console.error('Failed to submit route:', error)
    showToast('操作失败，请重试！', 'error')
  }
}


const closeModal = () => {
  showCreateModal.value = false
  showEditModal.value = false
  showViewModal.value = false
  selectedRoute.value = null
  resetRouteForm()
}

// ==================== 路径查看功能 ====================
// 查看线路路径
const viewRoutePath = async (route: Route) => {
  console.log('查看线路路径:', route)

  // 显示模态框和加载状态
  showRoutePathModal.value = true
  isLoadingPath.value = true
  routePathData.value = null

  try {
    // 调用后台接口获取路径数据
    const url = `${GATEWAY_URL.TRACE_READ}/api/Address/GetMapRoute?origin=${encodeURIComponent(route.start_address || route.starting_point)}&destination=${encodeURIComponent(route.destination_address || route.destination)}&strategy=0&vehicleType=1`

    console.log('调用路径查看API:', url)

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const data = await response.json()
    console.log('路径查看API响应:', data)

    if (data.code === 200 && data.data) {
      routePathData.value = data.data

      // 简单延迟后初始化地图，确保DOM已渲染
      setTimeout(() => {
        initRoutePathMap()
      }, 1000)

      showToast('路径数据加载成功！', 'success')
    } else {
      throw new Error(data.message || '路径数据获取失败')
    }
  } catch (error) {
    console.error('路径查看API调用失败:', error)

    // 检查具体的错误类型
    const errorMessage = error instanceof Error ? error.message : String(error)

    if (error instanceof TypeError && errorMessage.includes('fetch')) {
      showToast('无法连接到后台服务，请检查网关服务是否正常', 'error')
    } else if (errorMessage.includes('HTTP 404')) {
      showToast('API接口不存在，请检查后台服务配置', 'error')
    } else if (errorMessage.includes('HTTP 500')) {
      showToast('后台服务内部错误，请检查服务日志', 'error')
    } else {
      showToast(`路径数据加载失败：${errorMessage}`, 'error')
    }

    routePathData.value = null
  } finally {
    isLoadingPath.value = false
  }
}

// 关闭路径查看模态框
const closeRoutePathModal = () => {
  showRoutePathModal.value = false
  routePathData.value = null
  isLoadingPath.value = false

  // 销毁地图实例
  if ((window as any).routePathMapInstance) {
    (window as any).routePathMapInstance.destroy()
      ; (window as any).routePathMapInstance = null
  }
}

// 智能等待地图API加载完成
const waitForMapAPIAndInit = () => {
  let attempts = 0
  const maxAttempts = 20 // 最多尝试20次，总共10秒

  const checkAndInit = () => {
    attempts++
    console.log(`尝试初始化地图 (${attempts}/${maxAttempts})`)

    // 检查高德地图API是否已加载
    if (window.AMap && window.AMap.Map) {
      console.log('✅ 高德地图基础API已加载')

      // 再检查DOM是否准备好
      const mapContainer = document.getElementById('routePathMap')
      if (mapContainer) {
        console.log('✅ DOM容器已准备好，开始初始化地图')
        initRoutePathMap()
        return
      } else {
        console.log('⏳ DOM容器未准备好，继续等待...')
      }
    } else {
      console.log('⏳ 高德地图API未完全加载，继续等待...')
    }

    // 如果还没准备好，继续等待
    if (attempts < maxAttempts) {
      setTimeout(checkAndInit, 500)
    } else {
      console.error('❌ 等待地图API加载超时')
      showToast('地图加载超时，请刷新页面重试！', 'error')
    }
  }

  // 立即开始检查
  checkAndInit()
}

// 初始化路径查看地图 - 确保API加载后再初始化
const initRoutePathMap = () => {
  console.log('🗺️ 开始初始化路径查看地图...')

  if (!routePathData.value) {
    console.error('❌ 路径数据未准备好')
    return
  }

  const mapContainer = document.getElementById('routePathMap')
  if (!mapContainer) {
    console.error('❌ 地图容器未找到')
    return
  }

  // 检查高德地图API是否已加载，如果没有则加载
  if (!window.AMap) {
    console.log('⏳ 高德地图API未加载，开始加载...')
    loadAMapScriptForRouteView().then(() => {
      console.log('✅ 高德地图API加载完成，开始创建地图')
      createRoutePathMap()
    }).catch(error => {
      console.error('❌ 高德地图API加载失败:', error)
      showToast('地图加载失败，请检查网络连接！', 'error')
    })
    return
  }

  console.log('✅ 高德地图API已存在，直接创建地图')
  createRoutePathMap()
}

// 为路径查看加载高德地图API
const loadAMapScriptForRouteView = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof window.AMap !== 'undefined') {
      resolve()
      return
    }

    // 检查是否已有脚本在加载
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]')
    if (existingScript) {
      console.log('⏳ 高德地图脚本已在加载中，等待完成...')
      const checkLoaded = () => {
        if (window.AMap) {
          resolve()
        } else {
          setTimeout(checkLoaded, 100)
        }
      }
      checkLoaded()
      return
    }

    console.log('📦 创建高德地图脚本标签...')
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=1.4.15&key=2870ab6f23360ed13cfdbbd18f990f84&plugin=AMap.Geocoder,AMap.PlaceSearch,AMap.Driving,AMap.DragRoute,AMap.Scale,AMap.ToolBar`
    script.async = true
    script.onload = () => {
      console.log('✅ 高德地图脚本加载成功')
      resolve()
    }
    script.onerror = () => {
      console.error('❌ 高德地图脚本加载失败')
      reject(new Error('高德地图加载失败，请检查API Key是否正确'))
    }
    document.head.appendChild(script)
  })
}

// 创建路径查看地图
const createRoutePathMap = () => {

  try {
    const mapData = routePathData.value
    console.log('📍 地图数据:', mapData)

    // 使用后台返回的地图中心点和缩放级别
    const mapCenter = mapData.mapCenter ?
      [mapData.mapCenter.longitude, mapData.mapCenter.latitude] :
      [116.397428, 39.90923] // 默认北京

    const map = new window.AMap.Map('routePathMap', {
      zoom: mapData.suggestedZoom || 10,
      center: mapCenter,
      mapStyle: 'amap://styles/normal',
      resizeEnable: true
    })

    console.log('🗺️ 地图中心点:', mapCenter)
    console.log('🔍 建议缩放级别:', mapData.suggestedZoom)

    console.log('✅ 地图实例创建成功')

      // 保存地图实例
      ; (window as any).routePathMapInstance = map

    // 等待地图完全加载后再添加内容
    map.on('complete', () => {
      console.log('🎯 地图加载完成，开始添加路径内容')

      // 检查后台返回的路径数据
      console.log('📊 检查路径坐标数量:', mapData.pathCoordinates?.length)

      if (mapData.pathCoordinates && mapData.pathCoordinates.length > 2) {
        console.log('🛣️ 使用后台返回的详细路径数据（多个途径点）')
        drawBackendRoute(map, mapData)
      } else {
        // 如果只有起终点，尝试高德地图路径规划
        const startPoint = mapData.startPoint?.coordinate
        const endPoint = mapData.endPoint?.coordinate

        if (startPoint?.longitude && startPoint?.latitude &&
          endPoint?.longitude && endPoint?.latitude) {
          console.log('🚗 后台只有起终点，尝试高德地图路径规划')
          drawRealDrivingRoute(map, mapData)
        } else {
          console.warn('⚠️ 无有效坐标数据')
          showToast('无法获取有效的路径坐标！', 'warning')
        }
      }

      // 添加地图控件（简化版本）
      try {
        // 只添加基本控件，避免兼容性问题
        if (window.AMap.Scale) {
          map.addControl(new window.AMap.Scale())
          console.log('✅ 比例尺控件添加成功')
        }
        if (window.AMap.ToolBar) {
          map.addControl(new window.AMap.ToolBar())
          console.log('✅ 工具栏控件添加成功')
        }
      } catch (error) {
        console.warn('⚠️ 地图控件添加失败，跳过控件:', error)
        // 控件添加失败不影响主要功能
      }
    })

  } catch (error) {
    console.error('❌ 地图初始化失败:', error)
    showToast('地图初始化失败！', 'error')
  }
}

// 使用后台返回的详细路径数据绘制真实路线
const drawBackendRoute = (map: any, mapData: any) => {
  console.log('🛣️ 开始使用后台详细路径数据')
  console.log('📊 路径坐标数量:', mapData.pathCoordinates?.length)

  const startCoord = mapData.startPoint?.coordinate
  const endCoord = mapData.endPoint?.coordinate

  if (!startCoord || !endCoord) {
    console.error('❌ 起点或终点坐标无效')
    return
  }

  // 添加起点标记
  const startMarker = new window.AMap.Marker({
    position: [startCoord.longitude, startCoord.latitude],
    title: '起点: ' + (mapData.startPoint.address || '未知地址'),
    content: `<div class="custom-marker start-marker">起</div>`
  })
  map.add(startMarker)

  // 添加终点标记
  const endMarker = new window.AMap.Marker({
    position: [endCoord.longitude, endCoord.latitude],
    title: '终点: ' + (mapData.endPoint.address || '未知地址'),
    content: `<div class="custom-marker end-marker">终</div>`
  })
  map.add(endMarker)

  // 使用后台返回的路径坐标绘制路线
  if (mapData.pathCoordinates && mapData.pathCoordinates.length > 0) {
    const pathCoords = mapData.pathCoordinates
      .filter((coord: any) => coord.longitude && coord.latitude && coord.longitude !== 0 && coord.latitude !== 0)
      .map((coord: any) => [coord.longitude, coord.latitude])

    console.log('🛣️ 有效路径坐标数量:', pathCoords.length)

    if (pathCoords.length >= 2) {
      // 绘制真实路径线
      const polyline = new window.AMap.Polyline({
        path: pathCoords,
        strokeColor: '#3366FF',
        strokeWeight: 6,
        strokeOpacity: 0.8,
        strokeStyle: 'solid'
      })
      map.add(polyline)

      console.log('✅ 后台路径数据绘制成功')

      // 显示路径信息
      const routeInfo = mapData.routeInfo
      if (routeInfo) {
        showToast(`真实路径显示完成！\n距离：${routeInfo.distanceText}\n时间：${routeInfo.durationText}`, 'success')
      } else {
        showToast('真实路径显示完成！', 'success')
      }

      // 自适应显示所有内容
      setTimeout(() => {
        map.setFitView([startMarker, endMarker, polyline], false, [50, 50, 50, 50])
        console.log('🎯 地图视野调整完成')
      }, 500)

    } else {
      console.warn('⚠️ 后台路径坐标不足，使用直线连接')
      drawFallbackRoute(map, mapData)
    }
  } else {
    console.warn('⚠️ 无后台路径坐标，使用直线连接')
    drawFallbackRoute(map, mapData)
  }
}

// 使用高德地图真实驾车路径规划
const drawRealDrivingRoute = (map: any, mapData: any) => {
  console.log('🚗 开始真实驾车路径规划')

  const startCoord = mapData.startPoint?.coordinate
  const endCoord = mapData.endPoint?.coordinate

  if (!startCoord || !endCoord) {
    console.error('❌ 起点或终点坐标无效')
    return
  }

  console.log('📍 起点坐标:', [startCoord.longitude, startCoord.latitude])
  console.log('📍 终点坐标:', [endCoord.longitude, endCoord.latitude])

  // 检查Driving插件是否可用
  if (!window.AMap.Driving) {
    console.error('❌ AMap.Driving插件未加载')
    showToast('路径规划插件未加载！', 'error')
    return
  }

  // 创建驾车路径规划实例
  const driving = new window.AMap.Driving({
    map: map,
    panel: null, // 不显示文字面板
    policy: window.AMap.DrivingPolicy.LEAST_TIME, // 最短时间策略

    // 自定义路线样式
    polyOptions: {
      strokeColor: '#3366FF',
      strokeWeight: 6,
      strokeOpacity: 0.8,
      strokeStyle: 'solid'
    },

    // 自定义标记样式
    markerOptions: {
      startMarkerOptions: {
        content: `<div class="custom-marker start-marker">起</div>`,
        title: '起点: ' + (mapData.startPoint.address || '未知地址')
      },
      endMarkerOptions: {
        content: `<div class="custom-marker end-marker">终</div>`,
        title: '终点: ' + (mapData.endPoint.address || '未知地址')
      }
    }
  })

  console.log('🛣️ 开始路径规划计算...')

  // 执行路径规划
  const startLngLat = new window.AMap.LngLat(startCoord.longitude, startCoord.latitude)
  const endLngLat = new window.AMap.LngLat(endCoord.longitude, endCoord.latitude)

  driving.search(startLngLat, endLngLat, (status: string, result: any) => {
    console.log('🎯 路径规划结果:', status)

    if (status === 'complete' && result.routes && result.routes.length > 0) {
      console.log('✅ 真实道路路径规划成功！')
      console.log('📊 路径详情:', result.routes[0])

      // 显示路径信息
      const route = result.routes[0]
      const distance = (route.distance / 1000).toFixed(1) + '公里'
      const duration = Math.ceil(route.time / 60) + '分钟'

      showToast(`真实路径规划完成！\n距离：${distance}\n时间：${duration}`, 'success')

      // 自适应显示路线
      setTimeout(() => {
        map.setFitView()
        console.log('🎯 地图视野自适应完成')
      }, 1000)

    } else if (status === 'no_data') {
      console.warn('⚠️ 无法规划路径，可能距离太远或无可行路线')
      showToast('无法规划路径，距离可能太远。显示直线连接。', 'warning')
      // 降级到直线显示
      drawFallbackRoute(map, mapData)

    } else {
      console.error('❌ 路径规划失败:', status, result)
      showToast('路径规划失败，显示直线连接', 'warning')
      // 降级到直线显示
      drawFallbackRoute(map, mapData)
    }
  })
}

// 降级方案：显示直线连接和标记
const drawFallbackRoute = (map: any, mapData: any) => {
  console.log('📏 使用降级方案：直线连接')

  const startCoord = mapData.startPoint?.coordinate
  const endCoord = mapData.endPoint?.coordinate

  if (!startCoord || !endCoord) return

  // 添加起点标记
  const startMarker = new window.AMap.Marker({
    position: [startCoord.longitude, startCoord.latitude],
    title: '起点: ' + (mapData.startPoint.address || '未知地址'),
    content: `<div class="custom-marker start-marker">起</div>`
  })
  map.add(startMarker)

  // 添加终点标记
  const endMarker = new window.AMap.Marker({
    position: [endCoord.longitude, endCoord.latitude],
    title: '终点: ' + (mapData.endPoint.address || '未知地址'),
    content: `<div class="custom-marker end-marker">终</div>`
  })
  map.add(endMarker)

  // 绘制直线连接
  const line = new window.AMap.Polyline({
    path: [
      [startCoord.longitude, startCoord.latitude],
      [endCoord.longitude, endCoord.latitude]
    ],
    strokeColor: '#FF6B6B',
    strokeWeight: 4,
    strokeOpacity: 0.8,
    strokeStyle: 'dashed'
  })
  map.add(line)

  // 自适应显示
  setTimeout(() => {
    map.setFitView([startMarker, endMarker, line], false, [50, 50, 50, 50])
    console.log('✅ 降级方案显示完成')
  }, 500)
}

// 使用后台返回的坐标绘制路径
const drawPathFromCoordinates = (map: any, mapData: any) => {
  console.log('📊 开始使用后台坐标绘制路径')
  console.log('🔍 起点数据:', mapData.startPoint)
  console.log('🔍 终点数据:', mapData.endPoint)
  console.log('🔍 路径坐标数量:', mapData.pathCoordinates?.length)

  const markers: any[] = []
  const lines: any[] = []

  // 添加起点标记
  if (mapData.startPoint?.coordinate?.longitude && mapData.startPoint?.coordinate?.latitude) {
    console.log('📍 添加起点标记:', [mapData.startPoint.coordinate.longitude, mapData.startPoint.coordinate.latitude])
    const startMarker = new window.AMap.Marker({
      position: [mapData.startPoint.coordinate.longitude, mapData.startPoint.coordinate.latitude],
      title: '起点: ' + (mapData.startPoint.address || '未知地址'),
      content: `<div class="custom-marker start-marker">起</div>`
    })
    map.add(startMarker)
    markers.push(startMarker)
  } else {
    console.warn('⚠️ 起点坐标无效')
  }

  // 添加终点标记
  if (mapData.endPoint?.coordinate?.longitude && mapData.endPoint?.coordinate?.latitude) {
    console.log('📍 添加终点标记:', [mapData.endPoint.coordinate.longitude, mapData.endPoint.coordinate.latitude])
    const endMarker = new window.AMap.Marker({
      position: [mapData.endPoint.coordinate.longitude, mapData.endPoint.coordinate.latitude],
      title: '终点: ' + (mapData.endPoint.address || '未知地址'),
      content: `<div class="custom-marker end-marker">终</div>`
    })
    map.add(endMarker)
    markers.push(endMarker)
  } else {
    console.warn('⚠️ 终点坐标无效')
  }

  // 绘制路径线
  if (mapData.pathCoordinates && mapData.pathCoordinates.length > 0) {
    const pathCoords = mapData.pathCoordinates
      .filter((coord: any) => coord.longitude && coord.latitude && coord.longitude !== 0 && coord.latitude !== 0)
      .map((coord: any) => [coord.longitude, coord.latitude])

    console.log('🛣️ 有效路径坐标数量:', pathCoords.length)
    console.log('🛣️ 路径坐标详情:', pathCoords)

    if (pathCoords.length >= 2) {
      // 如果只有起点和终点，绘制直线；如果有更多点，绘制完整路径
      const strokeStyle = pathCoords.length === 2 ? 'dashed' : 'solid'
      const strokeColor = pathCoords.length === 2 ? '#FF6B6B' : '#3366FF'

      const polyline = new window.AMap.Polyline({
        path: pathCoords,
        strokeColor: strokeColor,
        strokeWeight: 6,
        strokeOpacity: 0.8,
        strokeStyle: strokeStyle
      })
      map.add(polyline)
      lines.push(polyline)

      if (pathCoords.length === 2) {
        console.log('✅ 起终点直线连接绘制成功')
      } else {
        console.log('✅ 完整路径线绘制成功')
      }
    } else {
      console.warn('⚠️ 有效路径坐标不足')
    }
  } else {
    console.warn('⚠️ 无路径坐标数据')
  }

  // 自适应显示所有内容
  const allObjects = [...markers, ...lines]
  if (allObjects.length > 0) {
    setTimeout(() => {
      map.setFitView(allObjects, false, [50, 50, 50, 50]) // 添加边距
      console.log('🎯 地图视野调整完成')
    }, 500)
  }

  console.log('✅ 路径绘制完成')
}

// 绘制直线连接（当没有详细路径时）
const drawDirectLineFromMarkers = (map: any, mapData: any) => {
  console.log('📏 绘制直线连接起终点')

  const startCoord = mapData.startPoint?.coordinate
  const endCoord = mapData.endPoint?.coordinate

  if (startCoord?.longitude && startCoord?.latitude &&
    endCoord?.longitude && endCoord?.latitude) {

    const line = new window.AMap.Polyline({
      path: [
        [startCoord.longitude, startCoord.latitude],
        [endCoord.longitude, endCoord.latitude]
      ],
      strokeColor: '#FF6B6B',
      strokeWeight: 4,
      strokeOpacity: 0.8,
      strokeStyle: 'dashed'
    })
    map.add(line)

    // 自适应显示
    setTimeout(() => {
      map.setFitView([line], false, [50, 50, 50, 50])
    }, 500)

    console.log('✅ 直线连接绘制完成')
  }
}

// 直接连线（最后备用方案）
const drawDirectLine = (map: any, startPoint: any, endPoint: any) => {
  console.log('使用直线连接起点和终点')

  // 添加起点标记
  const startMarker = new window.AMap.Marker({
    position: [startPoint.longitude, startPoint.latitude],
    title: '起点',
    content: `<div class="custom-marker start-marker">起</div>`
  })
  map.add(startMarker)

  // 添加终点标记
  const endMarker = new window.AMap.Marker({
    position: [endPoint.longitude, endPoint.latitude],
    title: '终点',
    content: `<div class="custom-marker end-marker">终</div>`
  })
  map.add(endMarker)

  // 绘制直线
  const line = new window.AMap.Polyline({
    path: [
      [startPoint.longitude, startPoint.latitude],
      [endPoint.longitude, endPoint.latitude]
    ],
    strokeColor: '#FF6B6B',
    strokeWeight: 4,
    strokeOpacity: 0.8,
    strokeStyle: 'dashed'
  })
  map.add(line)

  // 自适应显示
  map.setFitView([startMarker, endMarker, line])
  showToast('显示直线路径（备用方案）', 'info')
}

const resetRouteForm = () => {
  Object.assign(routeForm, {
    id: 0,
    starting_point: '',
    start_address: '',
    destination: '',
    destination_address: '',
    is_out: true,
    consignor_name: '',
    phone: '',
    consignor_unit: '',
    description: '',
    total_distance: '',
    estimated_time: '',
    createdBy: '王大锤'
  })
}

// 工具函数
const formatAddress = (address: Address) => {
  return `${address.province}${address.city}${address.district}${address.detail}`
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    planned: '已规划',
    in_progress: '进行中',
    completed: '已完成'
  }
  return statusMap[status] || status
}

const getWaypointStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待到达',
    arrived: '已到达',
    departed: '已离开'
  }
  return statusMap[status] || status
}

// Toast 通知函数
const showToast = (message: string, type: 'success' | 'error' | 'warning' | 'info' = 'success') => {
  toast.message = message
  toast.type = type
  toast.show = true

  setTimeout(() => {
    toast.show = false
  }, 3000)
}

const getToastIcon = () => {
  switch (toast.type) {
    case 'success': return 'icon-check'
    case 'error': return 'icon-error'
    case 'warning': return 'icon-warning'
    case 'info': return 'icon-info'
    default: return 'icon-check'
  }
}

// 地图相关方法
const openMapPicker = (mode: 'start' | 'end') => {
  mapPickerMode.value = mode
  mapPickerTitle.value = mode === 'start' ? '选择起点' : '选择终点'
  showMapPicker.value = true
}

const closeMapPicker = () => {
  showMapPicker.value = false
}

const handleMapConfirm = (point: MapPoint) => {
  if (point.type === 'start') {
    // 清空之前的计算结果（重新选择起点时）
    routeForm.total_distance = ''
    routeForm.estimated_time = ''

    routeForm.starting_point = point.name || '起点'
    routeForm.start_address = point.address
    routeCoordinates.start = { lng: point.lng, lat: point.lat }
    showToast('起点信息已填入！', 'success')
  } else if (point.type === 'end') {
    // 清空之前的计算结果（重新选择终点时）
    routeForm.total_distance = ''
    routeForm.estimated_time = ''

    routeForm.destination = point.name || '终点'
    routeForm.destination_address = point.address
    routeCoordinates.end = { lng: point.lng, lat: point.lat }
    showToast('终点信息已填入！', 'success')
  }

  // 检查是否可以计算路线，如果可以则自动计算
  updateCanCalculateRoute()

  // 如果起点和终点都已选择，自动计算路线
  if (canCalculateRoute.value) {
    // 延迟一下再计算，让用户看到选点成功的提示
    setTimeout(() => {
      calculateRoute()
    }, 500)
  }

  closeMapPicker()
}

// 更新是否可以计算路线的状态
const updateCanCalculateRoute = () => {
  canCalculateRoute.value = routeCoordinates.start.lng !== 0 &&
    routeCoordinates.start.lat !== 0 &&
    routeCoordinates.end.lng !== 0 &&
    routeCoordinates.end.lat !== 0
}

// 计算路线距离和时间 - 使用后台API
const calculateRoute = async () => {
  if (!canCalculateRoute.value) {
    showToast('请先选择起点和终点！', 'warning')
    return
  }

  isCalculating.value = true

  try {
    // 构建起点和终点字符串（经度,纬度格式）
    const origin = `${routeCoordinates.start.lng},${routeCoordinates.start.lat}`
    const destination = `${routeCoordinates.end.lng},${routeCoordinates.end.lat}`

    console.log('调用后台路线计算API:', {
      origin,
      destination,
      strategy: 0, // 速度优先
      vehicleType: 1 // 货车
    })

    // 调用后台路线计算API
    const url = `${GATEWAY_URL.TRACE_READ}/api/Address/CalculateRoute?origin=${encodeURIComponent(origin)}&destination=${encodeURIComponent(destination)}&strategy=0&showSteps=true&vehicleType=1`

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const data = await response.json()
    console.log('后台路线计算API响应:', data)

    if (data.code === 200 && data.data) {
      const routeData = data.data

      // 使用后台返回的格式化文本，如果没有则自己格式化
      const distanceText = routeData.distanceText || formatDistance(routeData.distance)
      const timeText = routeData.durationText || formatDuration(routeData.duration)

      // 更新表单
      routeForm.total_distance = distanceText
      routeForm.estimated_time = timeText

      // 显示详细信息
      let toastMessage = `路线计算完成！\n距离：${distanceText}\n预计时间：${timeText}`

      // 如果有过路费信息，也显示出来
      if (routeData.tolls && routeData.tolls > 0) {
        toastMessage += `\n过路费：${routeData.tolls}元`
      }

      // 如果有红绿灯信息，也显示出来
      if (routeData.trafficLights && routeData.trafficLights > 0) {
        toastMessage += `\n红绿灯：${routeData.trafficLights}个`
      }

      showToast(toastMessage, 'success')

      console.log('路线计算结果:', {
        distance: distanceText,
        time: timeText,
        rawDistance: routeData.distance,
        rawDuration: routeData.duration,
        tolls: routeData.tolls,
        trafficLights: routeData.trafficLights,
        steps: routeData.steps?.length || 0
      })
    } else {
      throw new Error(data.message || '路线计算失败')
    }
  } catch (error) {
    console.error('后台路线计算API调用失败:', error)
    showToast('路线计算失败，请检查起点和终点是否正确！', 'error')
  } finally {
    isCalculating.value = false
  }
}

// 格式化距离（如果后台没有返回格式化文本）
const formatDistance = (distance: number): string => {
  if (distance >= 1000) {
    return `${(distance / 1000).toFixed(1)}公里`
  } else {
    return `${distance}米`
  }
}

// 格式化时间（如果后台没有返回格式化文本）
const formatDuration = (duration: number): string => {
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}
</script>

<style scoped>
/* 复用订单管理页面的样式 */
.route-management {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h1 {
  margin: 0;
  color: #333;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  min-width: 150px;
}

.form-group label {
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

.form-control {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.form-actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #555;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-planned {
  background: #fff3cd;
  color: #856404;
}

.status-in_progress {
  background: #cce5ff;
  color: #004085;
}

.status-completed {
  background: #d1ecf1;
  color: #0c5460;
}

.status-out {
  background: #d4edda;
  color: #155724;
}

.status-in {
  background: #fff3cd;
  color: #856404;
}

.status-arrived {
  background: #d4edda;
  color: #155724;
}

.status-departed {
  background: #d1ecf1;
  color: #0c5460;
}

.actions {
  display: flex;
  gap: 5px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #eee;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-selector label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.page-size-select {
  width: 80px;
  padding: 4px 8px;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  max-width: 900px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.form-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.form-row .form-group {
  flex: 1;
}

.waypoints-section {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h4 {
  margin: 0;
  color: #555;
}

.waypoint-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #f9f9f9;
}

.waypoint-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.waypoint-header h5 {
  margin: 0;
  color: #666;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.route-details {
  max-width: 600px;
}

.detail-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-section:last-child {
  border-bottom: none;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #555;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.detail-row .label {
  min-width: 100px;
  font-weight: 500;
  color: #666;
}

.detail-row .value {
  flex: 1;
  color: #333;
}

.waypoint-detail {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  background: #f9f9f9;
}

.waypoint-detail h5 {
  margin: 0 0 10px 0;
  color: #666;
}

.input-with-button {
  display: flex;
  gap: 10px;
  align-items: center;
}

.input-with-button .form-control {
  flex: 1;
}

.input-with-status {
  position: relative;
  display: flex;
  align-items: center;
}

.input-with-status .form-control {
  flex: 1;
  padding-right: 100px;
  /* 为状态指示器留出空间 */
}

.status-indicator {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.status-indicator.calculating {
  background: #e3f2fd;
  color: #1976d2;
  border: 1px solid #bbdefb;
}

.status-indicator.success {
  background: #e8f5e8;
  color: #2e7d32;
  border: 1px solid #c8e6c9;
}

.status-indicator .icon-loading {
  animation: spin 1s linear infinite;
}

.status-indicator .icon-check::before {
  content: '✓';
}

.status-indicator .icon-loading::before {
  content: '⟳';
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.map-modal {
  max-width: 90vw;
  width: 1000px;
  max-height: 90vh;
  padding: 0;
}

.icon-plus::before {
  content: '+';
  margin-right: 5px;
}

/* Toast 通知样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  min-width: 300px;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  animation: slideInRight 0.3s ease-out;
  backdrop-filter: blur(10px);
}

.toast-success {
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border-left: 4px solid #2E7D32;
}

.toast-error {
  background: linear-gradient(135deg, #f44336, #d32f2f);
  color: white;
  border-left: 4px solid #C62828;
}

.toast-warning {
  background: linear-gradient(135deg, #ff9800, #f57c00);
  color: white;
  border-left: 4px solid #E65100;
}

.toast-info {
  background: linear-gradient(135deg, #2196F3, #1976D2);
  color: white;
  border-left: 4px solid #0D47A1;
}

.toast-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toast-icon {
  font-size: 18px;
  font-weight: bold;
}

.toast-message {
  font-size: 14px;
  font-weight: 500;
  flex: 1;
}

/* 图标样式 */
.icon-check::before {
  content: '✓';
}

.icon-error::before {
  content: '✕';
}

.icon-warning::before {
  content: '⚠';
}

.icon-info::before {
  content: 'ℹ';
}

/* 动画效果 */
@keyframes slideInRight {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toast {
    left: 20px;
    right: 20px;
    min-width: auto;
  }
}

/* ==================== 路径查看模态框样式 ==================== */
.route-path-modal {
  max-width: 95vw;
  width: 1200px;
  max-height: 90vh;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  color: #666;
}

.loading-spinner .icon-loading {
  font-size: 24px;
  animation: spin 1s linear infinite;
}

.route-path-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.route-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-item .label {
  font-weight: 600;
  color: #495057;
  min-width: 80px;
}

.summary-item .value {
  color: #212529;
  font-weight: 500;
}

.map-container {
  width: 100%;
  height: 500px;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  overflow: hidden;
}

.route-map {
  width: 100%;
  height: 100%;
}

.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

.error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  color: #dc3545;
}

.error-message .icon-error {
  font-size: 24px;
}

/* 自定义地图标记样式 */
.custom-marker {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.start-marker {
  background: linear-gradient(135deg, #28a745, #20c997);
}

.end-marker {
  background: linear-gradient(135deg, #dc3545, #fd7e14);
}

/* 操作按钮间距调整 */
.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.actions .btn {
  white-space: nowrap;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .route-path-modal {
    width: 95vw;
    max-height: 95vh;
  }

  .route-summary {
    grid-template-columns: 1fr;
    gap: 10px;
    padding: 15px;
  }

  .map-container {
    height: 400px;
  }

  .actions {
    flex-direction: column;
    gap: 5px;
  }

  .actions .btn {
    width: 100%;
  }
}
</style>
